<?php
/**
 * MerchantsController class.
 * MerchantsController is for the list of merchants.
 * 
 * LBB Solutions Ltd. 版权所有 @ 2012.
 */
class MerchantsController extends ApiController
{
	/**
	 * API: merchants/index with search
	 */
	public function actionIndex()
	{
		$params = array();
		
		//get q=?
		$q = Yii::app()->request->getParam('q');
		if (!empty($q)) {
			$s_where = " AND (m.name LIKE :q OR m.biz_area LIKE :q OR m.address LIKE :q) ";
			$params[':q'] = "%{$q}%";
		}
		
		// get hid (id_user)
		$s_following = null;
		$hid = Yii::app()->request->getParam('hid');
		$key = Yii::app()->request->getParam('key');
		if (!empty($hid) and !empty($key)) {
			$id = $this->_auth($hid, $key);
			$s_following = ', (SELECT f.id_user FROM tbl_user_follow_merchant f
				WHERE f.id_merchant=m.id AND f.id_user=:id_user LIMIT 1) AS following_user_id ';
			$params[':id_user'] = $id;
		}
		
		// set the limit number and offset
		$offset = Yii::app()->request->getParam('offset', 0);
		$limit = Yii::app()->request->getParam('limit', 50);
		if ($limit > 50) $limit = 50;
		$s_limit = " LIMIT {$offset}, " . $limit;
		
		// get distance if lat=? and lng=?
		$s_distance = 'NULL AS distance, ';
		$latitude = Yii::app()->request->getParam('lat');
		$longitude= Yii::app()->request->getParam('lng');
		if (!empty($latitude) and !empty($longitude)) {
			$s_distance = '(6371 * acos(cos(radians(:lat)) * cos(radians(m.latitude)) * cos(radians(m.longitude) - radians(:lng)) + sin(radians(:lat)) * sin(radians(m.latitude)))) AS distance, ';
			$params[':lat'] = (double)$latitude;
			$params[':lng'] = (double)$longitude;
		}
		
		$sql_merchants = 'SELECT m.id AS id_merchant,
			m.name, m.address, m.biz_area, m.postcode, m.city, m.phone, m.url_logo, m.url_offer_img, m.currency_code, m.category_key, m.latitude, m.longitude, 
			' . $s_distance . ' t.cuisine_style, t.cuisine_type ' . $s_following . '
			FROM tbl_merchant_account m
			LEFT JOIN tbl_merchant_tags t ON m.id=t.id_merchant
			WHERE m.status=1 and m.name IS NOT NULL AND m.latitude IS NOT NULL AND m.longitude IS NOT NULL
			' . $s_where . '
			ORDER BY distance, m.name
			' . $s_limit;
		
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_merchants);
		$rows = $command->queryAll(true, $params);
		$connection->active = false;
		
		$this->_sendJSON(200, $this->_mkMerchants($rows));
	}
	
	/**
	 * API: merchants/following
	 * list the merchants I am following
	 */
	public function actionFollowing()
	{
		// get hid
		$hid = Yii::app()->request->getParam('hid');
		$key = Yii::app()->request->getParam('key');
		if (empty($hid) or empty($key)) {
			$this->_sendJSON(300, BUtils::T('no_login_following_merchants_msg'));
		}
		$id = $this->_auth($hid, $key);
		
		$params = array(
			':id' => $id,
		);
		
		// set the limit number and offset
		$offset = Yii::app()->request->getParam('offset', 0);
		$limit = Yii::app()->request->getParam('limit', 20);
		if ($limit > 20) $limit = 20;
		$s_limit = " LIMIT {$offset}, " . $limit;
		
		// get distance if lat=? and lng=?
		$s_distance = 'NULL AS distance, ';
		$latitude = Yii::app()->request->getParam('lat');
		$longitude= Yii::app()->request->getParam('lng');
		if (!empty($latitude) and !empty($longitude)) {
			$s_distance = '(6371 * acos(cos(radians(:lat)) * cos(radians(m.latitude)) * cos(radians(m.longitude) - radians(:lng)) + sin(radians(:lat)) * sin(radians(m.latitude)))) AS distance, ';
			$params[':lat'] = (double)$latitude;
			$params[':lng'] = (double)$longitude;
		}
		
		$sql_merchants = 'SELECT m.id AS id_merchant,
			m.name, m.address, m.biz_area, m.postcode, m.city, m.phone, m.url_logo, m.url_offer_img, m.currency_code, m.category_key, m.latitude, m.longitude, 
			' . $s_distance . ' t.cuisine_style, t.cuisine_type, 1 AS following
			FROM tbl_user_follow_merchant f
			INNER JOIN tbl_merchant_account m ON m.id=f.id_merchant
			LEFT JOIN tbl_merchant_tags t ON f.id_merchant=t.id_merchant
			WHERE f.id_user=:id
			ORDER BY f.action_time DESC
			' . $s_limit;
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_merchants);
		$rows = $command->queryAll(true, $params);
		$connection->active = false;
		
		$this->_sendJSON(200, $this->_mkMerchants($rows));
	}
	
	/**
	 * Make merchants list
	 * @param array $rows
	 * @return array
	 */
	protected function _mkMerchants($rows) {
		$categoriesIndex = BUtils::CategoriesNo();
		
		$merchants = array();
		foreach ($rows as $r) {
			//following_user_id
			if (!empty($r['following_user_id'])) {
				$following = 1;
			} elseif (!empty($r['following'])) {
				$following = (int)$r['following'];
			} else {
				$following = 0;
			}
			
			//tags
			$tags = array();
			if (!empty($r['cuisine_style'])) {
				foreach (explode(',', $r['cuisine_style']) as $t) {
					$tags[] = array($t, BUtils::T($t));
				}
			}
			if (!empty($r['cuisine_type'])) {
				foreach (explode(',', $r['cuisine_type']) as $t) {
					$tags[] = array($t, BUtils::T($t));
				}
			}
			
			//logo
			$url_logo = null;
			if (!empty($r['url_logo'])) {
				$url_logo = 'http://yamii.fi/business' . $r['url_logo'];
			}
			
			// $category
			$category = BUtils::T($r['category_key']);
			$cate_no = (int)$categoriesIndex[$r['category_key']];
			
			$merchants[] = array(
				'id' => $r['id_merchant'],
				'name' => $r['name'],
				'category' => $category,
				'category_no' => $cate_no,//new
				'url_logo' => $url_logo,
				'area' => empty($r['biz_area']) ? '' : $r['biz_area'],
				'address' => empty($r['address']) ? '' : $r['address'],
				'zip' => $r['postcode'],
				'city' => $r['city'],
				'phone' => MerchantObject::formatPhoneNumber($r['phone']),
				'distance' => empty($r['distance']) ? null : (float)$r['distance'],
				'lat' => (float)$r['latitude'],
				'lng' => (float)$r['longitude'],
				'brief' => $r['brief'],
				'tags' => $tags,
				'following' => $following,
			);
		}
		return $merchants;
	}
}